package com.libinyn.base.i18n.config.i18n;

import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;

import org.apache.tomcat.jni.Global;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 *  Springboot 国际化配置文件
 * @fileName: I18nConfig.java
 * @author: bin.li01
 * @date: 2017/12/20 22:54 
 * @version: v1.0.0
 */
@Configuration
public class I18nConfig  {

    private static Logger logger = LoggerFactory.getLogger(I18nConfig.class);

    /**
     * 对象的名称必须为localeResolver，Spring容器会自动加载，否则找不到。
     * @return
     */
    @Bean(name = "localeResolver")
    public MyLocaleResolver myLocaleResolver() {
        logger.info("#####cookieLocaleResolver---create");
        MyLocaleResolver myLocaleResolver = new MyLocaleResolver();
        myLocaleResolver.setDefaultLocale(Locale.CHINA);
        logger.info("#####cookieLocaleResolver:");
        return myLocaleResolver;
    }
    public static String getMessage(String key, Locale locale)
    {

        ResourceBundle resourceBundle = ResourceBundle.getBundle("i18n/messages",locale);

        if (resourceBundle.containsKey(key))
        {
            try {
                String s = new String(resourceBundle.getString(key).getBytes("ISO-8859-1"), "UTF-8");
                return resourceBundle.getString(key);
            } catch (UnsupportedEncodingException e) {
                logger.error("获取国际化失败！",e);
            }
        }

        return key;
    }

}
